package co.fitstart.admin.web.controller.system;


import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;
import co.fitstart.admin.entity.search.PrincipalSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CoachService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.coach.CoachStudentRelation;
import co.fitstart.entity.coach.PrincipalReportRelation;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.principal.PrincipalType;
import co.fitstart.entity.site.Site;


/**
 * @author mohanlan
 */
@Controller
@RequestMapping("/principals")
@MenuSetting("menu-system")
public class PrincipalController {
    private static final Logger logger = LoggerFactory.getLogger(PrincipalController.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CoachService coachService;
    
    @Autowired
    private SiteService siteService;
    
    /**
     * list all principals by site by page
     * 
     * @param principalType
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-principal-management")
    public ModelAndView list(@RequestParam(value = "principalType", required = false, defaultValue = "normal") String principalType,
                             Page page,
                             HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/normal-principal-list");
        
        List<Principal> principals = principalService.list(PrincipalType.NORMAL, page);
        
        modelAndView.addObject("principals", principals);
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }

    /**
     * list all principals by site by page
     * 
     * @param login
     * @param page
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "principalType=site")
    @MenuSetting("submenu-{highlight}-management")
    public ModelAndView list(@Secure Login login, 
                             Page page,
                             HttpServletRequest request) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/site-principal-list");
        
        if(login.hasSite()) {
            
            List<PrincipalReportRelation> relations = principalService.listRelation(login.getSite(), page);
            List<Principal> principals = CollectionUtils.extractPropertyList(relations, "coach");
            
            modelAndView.addObject("highlight", "site-principal");
            modelAndView.addObject("principals", principals);
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                
                List<Principal> principals;
                if(login.isAreaManager()) {
                    principals = principalService.listForAreaManager(sites, page);
                } else {
                    principals = principalService.listForAreaServer(sites, page);
                }
                
                modelAndView.addObject("principals", principals);
            }
            
            modelAndView.addObject("highlight", "site-principal");
        } else {
            
            List<Principal> principals = principalService.list(PrincipalType.SITE, page);
            
            modelAndView.addObject("highlight", "principal");
            modelAndView.addObject("principals", principals);
        }
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-{highlight}-management")
    public ModelAndView onSearch(@Secure Login login,
                                 PrincipalSearch principalSearch,
                                 @RequestParam(value = "siteId", required=false) Long siteId,
                                 Page page,
                                 HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("system/principal/site-principal-list");
        
        List<Principal> principals = new ArrayList<>();
        
        Site site = null;
        if(login.hasSite()) {
            site = login.getSite();
        } else if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        if(site != null) {
            List<Site> sites = new ArrayList<>();
            sites.add(site);
            
            principalSearch.setSites(sites);
        }
         
        if(login.isRoot() || login.isAdmin()) {
            principals = principalService.searchForAdminOrRoot(principalSearch, page);
            
            modelAndView.addObject("highlight", "principal");
        } else if(login.isAreaManager()) {
            if(site == null) {
                Principal areaManager = principalService.load(Principal.class, login.getId());
                
                principalSearch.setSites(siteService.listSite(areaManager));
            }
            
            principals = principalService.searchForAreaManager(principalSearch, page);
            
            modelAndView.addObject("highlight", "site-principal");
        } else {
            if(site == null && login.isAreaServer()) {
                Principal areaServer = principalService.load(Principal.class, login.getId());
                
                principalSearch.setSites(siteService.listSite(areaServer));
            }
            
            principals = principalService.searchForSiteManagerOrAreaServer(principalSearch, page);
            
            modelAndView.addObject("highlight", "site-principal");
        }
        
        modelAndView.addObject("principals", principals);
        modelAndView.addObject("page", page);
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        return modelAndView;
}
    
    /**
     * display principal view panel
     * 
     * @param login
     * @param id
     * @return 
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-{highlight}-management")
    public ModelAndView view(@Secure Login login, 
                             @PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-view");
        
        Principal principal = principalService.get(Principal.class, id);
        modelAndView.addObject("principal", principal);
        
        if(principal.isAreaManager() || principal.isAreaServer()) {
            modelAndView.addObject("sites", siteService.listSite(principal));
        } else if(principal.isSiteManager() || principal.isSiteServer()) {
            PrincipalReportRelation relation = principalService.loadRelation(principal);
            
            if(relation != null)  {
                modelAndView.addObject("site", relation.getSite());
            }
        } else if(principal.isCoach()) {
            List<PrincipalReportRelation> relations = principalService.listRelation(principal);
            for(PrincipalReportRelation relation : relations) {
            	
            	System.out.println("时间 : "+ relation.getAppointHours());
            }
            modelAndView.addObject("relations", relations);
        }
        
        if(login.isRoot() || login.isAdmin()) {
            modelAndView.addObject("highlight", "principal");
        } else {
            modelAndView.addObject("highlight", "site-principal");
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param id
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}/grid", method = RequestMethod.GET)
    public ModelAndView grid(@PathVariable("id") Long id,HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-view-grid");
        
        Principal principal = principalService.get(Principal.class, id);
        modelAndView.addObject("principal", principal);
        
        List<CoachStudentRelation> coachStudentRelations = coachService.listCoachStudentRelation(principal, page);
        modelAndView.addObject("coachStudentRelations", coachStudentRelations);
        
        modelAndView.addObject("total", coachStudentRelations.size());
        
        return modelAndView;
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value= "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-search");
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param id
     * @param managerId
     * @return
     */
    @RequestMapping(value = "/{id}/edit-appoint-days/{managerId}", method = RequestMethod.GET)
    public ModelAndView editAppointDays(@Secure Login login, 
                                        @PathVariable("id") Long id,
                                        @PathVariable("managerId") Long managerId) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-edit-appoint-days");
        
        Principal coach = principalService.get(Principal.class, id);
        
        Principal manager = principalService.get(Principal.class, managerId);
        
        PrincipalReportRelation relation = principalService.loadRelation(coach, manager);
        
        List<String> allAppointTime = siteService.getSiteAllAppointTime(relation.getSite().getId()); 
        
        String appointManyHour = relation.getAppointManyHour();
        ArrayList<Object> selectAppointHour = new ArrayList<>();
        if(appointManyHour != null) {
        	String[] splits = relation.getAppointManyHour().split(",");
        	
            for(String split:splits) {
            	
            	selectAppointHour.add(split);
            }
        }
             
        
        modelAndView.addObject("selectAppointHour",selectAppointHour);
        modelAndView.addObject("relation", relation);
        modelAndView.addObject("allAppointTime",allAppointTime);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param id
     * @param managerId
     * @param appointOption
     * @param appointDays
     * @return
     */
    @RequestMapping(value = "/{id}/edit-appoint-days/{managerId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEditAppointDays(@Secure Login login, 
                                                  @PathVariable("id") Long id,
                                                  @PathVariable("managerId") Long managerId,                                                  
                                                  @RequestParam("appointOption") String appointOption,                                                  
                                                  @RequestParam(value = "appointDays", required = false) List<Integer> appointDays,
                                                  @RequestParam(value = "appointHours",required = false)  List<String> appointHours) {
        Result result = new Result();
        
        try {
            if("all".equals(appointOption) || ("appoint".equals(appointOption) && appointDays != null && appointDays.size() > 0)) {
                Principal coach = principalService.get(Principal.class, id);
                
                Principal manager = principalService.get(Principal.class, managerId);
                
                coachService.editAppointDays(coach, manager, "all".equals(appointOption) ? null : appointDays);
                
                
                
                	
                coachService.editAppointHours(coach, manager, appointHours );
                
                
                
                result.success().message("更改教练可预约时间成功");
            } else {
                result.fail().message("更改教练可预约时间失败");
            }
        } catch (BusinessException e) {
            result.fail().message(e.getMessage());
        } catch (Exception e) {
            logger.error("onEditAppointDays() error:", e);
            result.fail().message("更改教练可预约时间失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param areaManagerId
     * @return
     */
    @RequestMapping(value = "/{principalId}/change-managed-sites", method = RequestMethod.GET)
    public ModelAndView editManagedSites(@Secure Login login, 
                                         @PathVariable("principalId") Long principalId) {
        
        ModelAndView modelAndView = new ModelAndView("system/principal/principal-edit-managed-sites");
        
        Principal areaManager = principalService.get(Principal.class, principalId);
        
        List<Site> sites = siteService.listSite(areaManager);
        
        if(!sites.isEmpty()) {
            List<Long> siteIds = new ArrayList<>();
            
            for(Site site : sites) {
                siteIds.add(site.getId());
            }
            
            modelAndView.addObject("siteIds", siteIds);
        }
        
        
        modelAndView.addObject("principalId", principalId);
        
        return modelAndView;
    }
    
    @RequestMapping(value = "/{principalId}/change-managed-sites", method = RequestMethod.PATCH)
    public @ResponseBody String onEditManagedSites(@Secure Login login, 
                                                   @PathVariable("principalId") Long principalId,
                                                   @RequestParam(value = "siteIds", required = false) Long[] siteIds) {
        Result result = new Result();
        
        try {
            Principal principal = principalService.get(Principal.class, principalId);
            
            List<Site> sites = new ArrayList<>();
            
            if(siteIds != null && siteIds.length > 0) {
                for(Long siteId : siteIds) {
                    sites.add(siteService.load(siteId));
                }
            }
            
            principalService.editManagedSites(principal, sites);
            
            result.success().message("指定门店成功");
        } catch (Exception e) {
            logger.error("onEditManagedSites() error:", e);
            result.fail().message("指定门店失败");
        }
        
        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/coaches", method = RequestMethod.POST)
    public @ResponseBody String listCoach(@RequestParam("siteId") Long siteId) {
        Result result = new Result();
        
        try {
            Site site  = siteService.load(siteId);
            List<Principal> coaches = coachService.listCoach(site);
            
            result.success().message("获取门店教练成功").data("coaches", coaches);
        } catch (Exception e) {
            logger.error("listCoach() error:", e);
            result.fail().message("获取门店教练失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
